package com.dis.service.service.impl;

import com.dis.common.constant.MessageConstant;
import com.dis.common.constant.PasswordConstant;
import com.dis.common.constant.StatusConstant;
import com.dis.common.context.BaseContext;
import com.dis.pojo.dto.UserDTO;
import com.dis.pojo.dto.UserLoginDTO;
import com.dis.pojo.entity.User;
import com.dis.common.exception.AccountLockedException;
import com.dis.common.exception.AccountNotFoundException;
import com.dis.service.mapper.UserMapper;
import com.dis.common.result.PageResult;
import com.dis.service.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.dis.pojo.dto.UserPageQueryDTO;
import com.dis.common.exception.PasswordErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 新增员工
     * @param userDTO
     */
    @Override
    public void save(UserDTO userDTO) {
        User user = new User();
        //对象属性拷贝
        BeanUtils.copyProperties(userDTO, user);
        //设置账号的状态，默认正常状态 1表示正常 0表示锁定
        user.setStatus(StatusConstant.ENABLE);
        //设置默认密码
        user.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置当前记录的创建时间和修改时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //设置当前记录创建人id和修改人id
        user.setCreateUser(BaseContext.getCurrentId());
        user.setUpdateUser(BaseContext.getCurrentId());

        userMapper.insert(user);
    }

    /**
     * 分页查询
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<User> page = userMapper.pageQuery(userPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        User user = User.builder()
                .status(status)
                .id(id)
                .build();
        userMapper.update(user);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        User user = userMapper.getById(id);
        user.setPassword("****");
        return user;
    }

    /**
     * 编辑员工信息
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateUser(BaseContext.getCurrentId());
        userMapper.update(user);
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }
}
